package com.zhitxx.selfpro.view

import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.webkit.WebView


/**
 * 自定义带进度条的WebView
 */
class CustomWebView : WebView {
    lateinit var indicatorHandler: IndicatorHandler
    lateinit var webProgressBar: WebProgressBar

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        init()
    }

    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    ) {
        init()
    }

    private var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            val progress = msg.obj as Int
            indicatorHandler.setProgress(progress)
        }
    }

    override fun getHandler(): Handler {
        return handler
    }

    fun init() {
        webProgressBar = WebProgressBar(context)
        webProgressBar.layoutParams = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        webProgressBar.visibility = View.GONE
        addView(webProgressBar)
        indicatorHandler = IndicatorHandler.instances.initWebProgress(webProgressBar)
        webChromeClient = ProgressWebClient(handler)

    }


}